package com.info.zhiduoduo.weixin.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.info.zhiduoduo.common.aliyunsdk.RecognizeIdcardService;
import com.info.zhiduoduo.common.aliyunsdk.pojo.BankMessage;
import com.info.zhiduoduo.common.baidusdk.OcrService;
import com.info.zhiduoduo.common.baidusdk.domain.OcrBankcardResult;
import com.info.zhiduoduo.common.baidusdk.domain.OcrIdcardResult;
import com.info.zhiduoduo.common.configs.UploadPathConfig;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.formbean.BaseAuthInfo;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.formbean.ImgDataFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.FileUtil;
import com.info.zhiduoduo.common.utils.IPUtil;
import com.info.zhiduoduo.common.utils.ImgBase64Util;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.formbean.BankCardElementFormBean;
import com.info.zhiduoduo.core.service.CommonService;
import com.info.zhiduoduo.core.service.common.DianDianYunService;
import com.info.zhiduoduo.core.service.common.DocService;
import com.info.zhiduoduo.core.service.impl.BankCardElementCertificationService;
import com.info.zhiduoduo.repository.entity.crm.CrmSystemDict;
import com.info.zhiduoduo.repository.entity.system.EnterpriseIndustry;
import com.info.zhiduoduo.weixin.formbean.system.PhoneFormBean;
import com.info.zhiduoduo.weixin.service.SystemService;

import io.swagger.annotations.ApiResponse;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "系统接口")
@RestController
@RequestMapping("/common")
public class CommonController {

	@Autowired
	SystemService systemService;

	@Value("${uploadpath}")
	private String uploadPath;

	@Value("${ossimgurl}")
	private String ossimgurl;

	@Value("${pic_bucket}")
	private String pic_bucket;

	@Autowired
	OcrService ocrService;
	@Autowired
	DocService docService;

	@Autowired
	UploadPathConfig uploadPathConfig;

	@Autowired
	DianDianYunService dianDianYunService;

	@Autowired
	BankCardElementCertificationService bankCardElementCertificationService;
	/**
	 获取手机验证码
	 */
	@PostMapping("/sendPhoneCode")
	public SmartResult sendPhoneCode(@RequestBody BaseSimpleFormBean<PhoneFormBean> baseSimpleFormBean) {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();

		return systemService.getPhoneCode(baseSimpleFormBean, IPUtil.getIpAddr(request));
	}

	/**
	 项目分类
	 */
	@PostMapping("/getProjectCategory")
	public SmartResult getProjectCategory(@RequestBody BaseAuthInfo baseAuthInfo) {
		return systemService.getProjectCategory(baseAuthInfo);
	}

	/**
	 行业分类
	 */
	@PostMapping("/getTradeCategory")
	public SmartResult getTradeCategory(@RequestBody BaseAuthInfo baseAuthInfo) {
		return systemService.getTradeCategory(baseAuthInfo);
	}

	/**
	 * 获取 城市开票类目 列表
	 * @param baseSimpleFormBean
	 * @return
	 */
	@PostMapping("/queryCityCategoryList")
	@ApiOperation("获取城市开票类目一级二级列表")
	public SmartResult queryAllCityCategoryList(@RequestBody BaseSimpleFormBean<Integer> baseSimpleFormBean){
		return systemService.queryAllCityCategoryList(baseSimpleFormBean);
	}



	/**
	 图片文件上传

	 @param file
	 @return
	 */
	@PostMapping(value = "/uploadImgFile")
	public SmartResult uploadImgFile(@RequestParam("file") MultipartFile file,
	                                 @RequestParam(value = "type", defaultValue = "0") int type,
	                                 @RequestParam(value = "idcardSide", defaultValue = "0") int idcardSide) {
		SmartResult smartResult = new SmartResult();
		if (!file.isEmpty()) {
			try {

				//文件夹名
				String fileFolder = DateUtil.getNowDateString(DateUtil.FORMAT_STYLE_8);

				File filePath = new File(uploadPath + "/" + fileFolder);
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				String imgFile = RandomUtil.createRandomNo("img_", ".jpg");
				String path = uploadPath + "/" + fileFolder + "/" + imgFile;
				File uploadFile = new File(path);
				BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(uploadFile));
				out.write(file.getBytes());
				out.flush();
				out.close();

				//上传OSS
				//OssHelper.getInstance().putFile(pic_bucket,fileFolder, imgFile, uploadFile);
				if (type == 1) {
					//银行卡识别
//					OcrBankcardResult bankcardResult = ocrService.recognizeBankcard(path);
					BankMessage bankcardResult = RecognizeIdcardService.checkBankCard(uploadFile);
					if (bankcardResult == null) {
						smartResult.setMsg("银行卡识别有误，请检查图片是否正确").setState(StatusMsg.StatusMsg_199.state);
						bankcardResult = new BankMessage();
					}

					bankcardResult.setImg(fileFolder + "/" + imgFile);
					smartResult.setObject(bankcardResult);
				} else if (type == 2){
					//身份证识别
//					OcrIdcardResult result = ocrService.recognizeIdcard(path, idcardSide);
					OcrIdcardResult result = RecognizeIdcardService.checkIdCard(uploadFile);

					if (result == null) {
						smartResult.setMsg("身份证识别有误，请检查图片是否正确").setState(StatusMsg.StatusMsg_199.state);
						result = new OcrIdcardResult();
					}
					result.setImg(fileFolder + "/" + imgFile);
					smartResult.setObject(result);
				}else {
					smartResult.setObject(fileFolder + "/" + imgFile);
				}

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				smartResult.setStateMsg(StatusMsg.StatusMsg_198);
				return smartResult;
			} catch (IOException e) {
				e.printStackTrace();
				smartResult.setStateMsg(StatusMsg.StatusMsg_198);
				return smartResult;
			}
		} else {
			smartResult.setStateMsg(StatusMsg.StatusMsg_102);
			return smartResult;
		}

		return smartResult;
	}


	@ApiOperation("上传文件")
	@PostMapping(value = "/uploadFile")
	public SmartResult uploadFile(@RequestParam("file") MultipartFile file) {
		SmartResult smartResult = new SmartResult();
		String filePath = FileUtil.uploadFileOwnName(uploadPath, file);
		if (StringUtil.isEmpty(filePath)) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_199);
		}
		smartResult.setObject(filePath);
		return smartResult;
	}

	/**
	 生成新的 截图   上传base64的数据

	 @param beanBaseSimpleFormBean
	 */
	@PostMapping(value = "/saveSnapshot")
	public SmartResult saveSnapshot(@RequestBody BaseSimpleFormBean<ImgDataFormBean> beanBaseSimpleFormBean) {

		SmartResult smartResult = new SmartResult();

		ImgDataFormBean imgDataFormBean = beanBaseSimpleFormBean.getReqdata();

		if (null != imgDataFormBean && !StringUtils.isEmpty(imgDataFormBean.getImgdata())) {
			String imgdata = imgDataFormBean.getImgdata();
			imgdata = imgdata.substring(imgdata.indexOf("base64,") + 7);

			String oss_object = DateUtil.getNowDateString(DateUtil.FORMAT_STYLE_8);
			String fileName = UUID.randomUUID().toString() + ".jpg";

			//物理地址
			String imgFilePath = uploadPath + "/" + oss_object + "/" + fileName;
			File file = ImgBase64Util.Base64ToImg(imgdata, imgFilePath);

			//String imgpath = OssHelper.imgUploadOss(uploadPath,imgDataFormBean.getImgdata());

			smartResult.setObject(oss_object + "/" + fileName);
		} else {
			smartResult.setStateMsg(StatusMsg.StatusMsg_102);
		}
		return smartResult;
	}

	@ApiOperation("上传身份证并通过点点云认证")
	@RequestMapping(value = "/uploadIdCardByDianDianYun", method = RequestMethod.POST)
	public SmartResult uploadIdCardByDianDianYun(@RequestParam("file") MultipartFile file,@RequestParam(value = "type") int type) {

		if (!file.isEmpty()) {
			try {
				String path = saveImg2Local(file);
				//根据类型确定身份证正反面，确定传入参数
//				String idCardSide = "";
//				if (1 == type) {
//					idCardSide = "front";
//				} else {
//					idCardSide = "back";
//				}
//				Map<String, Object> map = dianDianYunService.idCardAnalysis(uploadPathConfig.getUploadpath() + path, idCardSide);
				OcrIdcardResult result = RecognizeIdcardService.checkIdCard(new File(uploadPathConfig.getUploadpath() +path));
				if (result == null) {
					return SmartResult.fail("解析错误，请重新上传!");
				} else {
					return SmartResult.success(result);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return SmartResult.fail(StatusMsg.StatusMsg_198);
			}

		} else {
			return SmartResult.fail(StatusMsg.StatusMsg_102);
		}
	}

	private String saveImg2Local(MultipartFile file) throws IOException {
		//文件夹名
		String fileFolder = DateUtil.getNowDateString(DateUtil.FORMAT_STYLE_8);

		String uploadPath = uploadPathConfig.getUploadpath();
		File filePath = new File(uploadPath + "/" + fileFolder);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		String imgFile = RandomUtil.createRandomNo("img_", ".png");
		String path = uploadPath + "/" + fileFolder + "/" + imgFile;
		File uploadFile = new File(path);
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(uploadFile));
		out.write(file.getBytes());
		out.flush();
		out.close();

		return fileFolder + "/" + imgFile;
	}

	@ApiOperation("获取企业行业分类列表,GET方式")
	@GetMapping("/enterpriseIndustryList")
	public SmartResult<EnterpriseIndustry> getEnterpriseIndustryList() {
		return systemService.getEnterpriseIndustryList();
	}

	@ApiOperation("获取crm系统配置列表,GET方式")
	@GetMapping("/crmSystemDictList")
	public SmartResult<Map<Integer, List<CrmSystemDict>>> getCrmSystemDictList(@ApiParam("配置类型type,逗号分隔 ") @RequestParam(value = "typies") String typies) {
		return systemService.CrmSystemDictList(typies);
	}

	@Autowired
	CommonService commonService;

	@GetMapping("/sendEnterpriseNotice")
	public SmartResult sendEnterpriseNotice(@RequestParam("id") int id,@RequestParam("name") String name,@RequestParam("type") int type) {
		LogUtil.info("收到请求:" + id +  " name:" +  name + " type:" + type);
		return commonService.sendEnterpriseWeChatNotice(id, name, type);
	}

	@ApiOperation("验证银行卡信息")
	@GetMapping("validateCardInfo")
	public SmartResult validateCardInfo(@RequestParam("cardNo") String cardNo) {
		return commonService.validateCardInfo(cardNo);
	}

	@ApiOperation("下载文件")
	@GetMapping(value = "/downloadPath")
	public void downloadByPath(HttpServletResponse response,String filePath) {
		File file = new File(filePath);
		try {
			docService.downloadFile(response,file);
		} catch (Exception var4) {
			var4.printStackTrace();
		}
	}
	@ApiOperation("测试")
	@GetMapping(value = "/test")
	public SmartResult test() {
		try {
			FileInputStream in = new FileInputStream("/usr/local/zhiduoduotest/upload/zcxy.docx");// 载入文档
			POIFSFileSystem pfs = new POIFSFileSystem(in);
			HWPFDocument hwpf = new HWPFDocument(pfs);
			Range range = hwpf.getRange();
			return SmartResult.success(range.text());
		} catch (Exception e) {
		}
		return SmartResult.success();
	}

	@ApiOperation("银行卡要素认证")
	@PostMapping(value = "/bankCardElementCertification")
	public SmartResult bankCardElementCertification(@RequestBody BankCardElementFormBean formBean) {
		JSONObject result = bankCardElementCertificationService.postBankCardElement(formBean);
		return SmartResult.success(result.getInteger("result"));
	}
}
